package com.kevin.service.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j;

import com.kevin.model.db.DBSetInfo;
import com.kevin.model.db.DBTableModel;
import com.kevin.service.DBTabelService;

@Data
@Log4j
@EqualsAndHashCode(callSuper = false)
/**
 * table转model服务
 * @ClassName Tabel2ModelService
 * @author 朱鹏程
 * @date 2016年8月23日 上午9:23:00
 *
 */
public class OracleTabelService extends DBTabelService {

    public OracleTabelService() {
        super.init();
    }

    @Override
    public List<DBTableModel> getTables(String name) {
        List<DBTableModel> tableList = new ArrayList<>();
        String strsql = " SELECT t.*,(SELECT COMMENTS FROM user_tab_comments utc WHERE utc.TABLE_NAME=t.TABLE_NAME) AS COMMENTS FROM all_tables t WHERE owner='"
                + DBSetInfo.getDbUserName().toUpperCase() + "' ";
        if (name != null && name.length() > 0) {
            strsql += " AND TABLE_NAME like ? ";
        }
        strsql += " ORDER BY table_name";
        ResultSet rsmd = null;
        try (Connection conn = DriverManager.getConnection(DBSetInfo.getDbUrl(), DBSetInfo.getDbUserName(), DBSetInfo.getDbPassword())) {
            PreparedStatement pstmt = conn.prepareStatement(strsql);
            if (name != null && name.length() > 0) {
                pstmt.setString(1, "%" + name.toUpperCase() + "%");
            }
            pstmt.executeQuery();
            rsmd = pstmt.getResultSet();

            while (rsmd.next()) {
                String tableName = rsmd.getString("TABLE_NAME");
                Long dataSize = rsmd.getLong("SAMPLE_SIZE");
                String comments = rsmd.getString("COMMENTS");
                DBTableModel model = new DBTableModel();
                model.setTableName(tableName);
                model.setDataSize(dataSize);
                model.setTableComments(comments);
                tableList.add(model);
            }
        } catch (Exception e) {
            log.error("查询用户" + DBSetInfo.getDbUserName() + "下的表出错！", e);
        } finally {
            if (rsmd != null) {
                try {
                    rsmd.close();
                } catch (SQLException e) {
                    log.error("关闭出错！", e);
                }
            }

        }
        return tableList;
    }

}
